<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header">
        <span>批量导入商品</span>
      </div>
      <el-alert title="请先下载模板，按模板格式填写数据后再导入。" type="info" :closable="false" show-icon />
      <div style="margin: 16px 0;">
        <el-button type="primary" icon="el-icon-download" @click="importTemplate">下载模板</el-button>
        <el-checkbox v-model="upload.updateSupport" style="margin-left:16px;">是否更新已经存在的商品数据</el-checkbox>
      </div>
      <el-upload
        ref="upload"
        drag
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">仅允许导入xls、xlsx格式文件。</div>
      </el-upload>
      <div style="margin-top: 12px;">
        <el-button type="primary" @click="submitFileForm">开始导入</el-button>
        <el-button @click="resetUpload">重置</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
export default {
  name: "GoodsImport",
  data() {
    return {
      upload: {
        isUploading: false,
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/shangpins/shangpins/importData"
      }
    }
  },
  methods: {
    importTemplate() {
      this.download('shangpins/shangpins/importTemplate', {}, `goods_template_${new Date().getTime()}.xlsx`)
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    handleFileSuccess(response) {
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
    },
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },
    resetUpload() {
      this.$refs.upload.clearFiles()
      this.upload.isUploading = false
      this.upload.updateSupport = 0
    }
  }
}
</script>

